package net.kaaass.tools.gradequery.util;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

import java.io.*;

public class NetworkUtil {
    private static String UA = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36";
    public static File downloadCaptcha(String cookie) {
        File image = new File(StringUtil.randStr(16, StringUtil.SET_ENG + StringUtil.SET_NUM) + ".jpg");
        if (image.exists())
            image.delete();
        try {
            HttpResponse<InputStream> response = Unirest.get("http://cx.zjzs.net/INC/VerifyCode.aspx")
                    .header("Cookie", cookie).header("User-Agent", UA).asBinary();
            InputStream inputStream = response.getBody();
            OutputStream outputStream = new FileOutputStream(image);
            int l = -1;
            byte[] tmp = new byte[2048];
            while ((l = inputStream.read(tmp)) != -1) {
                outputStream.write(tmp);
            }
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (UnirestException e) {
            e.printStackTrace();
        }
        return image;
    }
}
